from manager_mysql import TodoManagerWithMysql
from flask import Flask, request

app = Flask(__name__)

# 对中文编码 JSON 格式时，使用原始中文
app.config['JSON_AS_ASCII'] = False

manager = TodoManagerWithMysql()
manager.init_db()
@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"

@app.route("/todos", methods=['GET'])
def list_todos():
    return {"todos": [x.__dict__ for x in manager.get_list()]}

@app.route("/todos", methods=['POST'])
def create_todo():
    """
    创建待办事项接口
        参数： title，表示待办事项的内容
        成功，返回已创建的待办事项 JSON 表示
    """
    if 'title' not in request.form:
        return '参数错误，必须提供 title 参数', 400
    todo = manager.create(request.form['title'])
    return todo.__dict__


@app.route("/todos/mark_completed", methods=['GET'])
def mark_completed():
    """
    创建待办事项接口
        参数： title，表示待办事项的内容
        成功，返回已创建的待办事项 JSON 表示
    """
    if 'id' not in request.args:
        return '参数错误，必须提供 id 参数', 400
    id = int(request.args['id'])
    todo = manager.mark_completed(id)
    if id is not None:
        return todo.__dict__
    else:
        return f'todo not found, id={id}', 404

@app.route("/todos/select_todo")
def select_todo():
        return {"todos": [x.__dict__ for x in manager.get_list()]}


@app.route("/todos/select_all_todo")
def select_all_todo():
    return {"todos": [x.__dict__ for x in manager.get_list()]}

@app.route("/todos/delete_todo", methods=['POST'])
def delete_todo():
    if 'id' not in request.form:
        return '参数错误，必须提供 id 参数', 400
    id = int(request.form['id'])
    todo = manager.delete_todo(id)
    if id is not None:
        return todo.__dict__
    else:
        return f'todo not found, id={id}', 404
    return "删除成功"

if __name__ == "__main__":
    app.run()